package com.societyGames.flashForms
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;

	public class FrameContainer extends SingleChildContainer
	{
		private var _desiredWidth:Number;
		private var _desiredHeight:Number;
		private var _body:Sprite;
		private var _borderTop:Number;
		private var _borderLeft:Number;
		private var _borderBottom:Number;
		private var _borderRight:Number;
		
		public function FrameContainer(body:Sprite, borderLeft:Number, borderRight:Number, borderTop:Number, borderBottom:Number)
		{
			this._body = body;
			this._borderLeft = borderLeft;
			this._borderRight = borderRight;
			this._borderTop = borderTop;
			this._borderBottom = borderBottom;
			
			this._body.y = 0;
			this.addChild(this._body);
			
			this._desiredWidth = width;
			this._desiredHeight = height;
		}
		
		public override function set width(value:Number):void
		{	
			if (value != this._desiredWidth)
			{
				this._desiredWidth = value;
				this._body.width = this._desiredWidth;
				recalculateChildWidth();
			}
		}
		
		public override function set height(value:Number):void
		{
			if (value != this._desiredHeight)
			{	
				this._desiredHeight = value;
				this._body.height = this._desiredHeight;
				recalculateChildHeight();
			}
		}

		public function get frame():Sprite
		{
			return this._body;
		}

		protected override function childSizeChangedHandler(event:Event):void
		{
			if (this._child != null)
			{
				this._child.x = this._borderLeft;
				this._child.y = this._borderTop;
				recalculateChildWidth();
				recalculateChildHeight();	
			}
		} 
		
		//Set space for the child.
		public function set innerWidth(value:Number):void
		{
			width = value + _borderLeft + _borderRight;
		}
		
		//Get space for the child.
		public function get innerWidth():Number
		{
			return _desiredWidth - (_borderLeft + _borderRight);
		}
		
		//Set space for the child.
		public function set innerHeight(value:Number):void
		{
			height = value + _borderBottom + _borderTop;
		}
		
		//Get space for the child.
		public function get innerHeight():Number
		{
			return _desiredHeight - (_borderBottom + _borderTop);
		}
		
		private function recalculateChildWidth():void
		{
			if (this._child != null)
			{
				this._child.width = _borderLeft + _borderRight > this._desiredWidth ? 0 : this._desiredWidth - (_borderLeft + _borderRight);	
			}
		}
		
		private function recalculateChildHeight():void
		{
			if (this._child != null)
			{
				this._child.height = _borderBottom + _borderTop > this._desiredHeight ? 0 : this._desiredHeight - (_borderBottom + _borderTop);
			}
		}
	}
}